package net.newsmth.smthapp.android.config;

import android.content.Context;
import android.content.SharedPreferences;


/**
 * Created by Hatsune Miku on 3/25/14.
 */
public class AppSettingsImpl implements AppSettings {


    //region Static members
    private static final String AppSettingsPreferenceKey = "AppSettings";
    private static final String UserKey = "User";
    private static final String TokenKey = "TokenKey";

    private static final AppSettings appSettingsInstance = new AppSettingsImpl();

    public static AppSettings getCurrent() {
        return appSettingsInstance;
    }
    //endregion

    //region Fields
    private AppApplication appContext;
    private SharedPreferences preferences;
    private String userName;
    private String token;
    //endregion

    //region Constructor
    public AppSettingsImpl() { }
    //endregion

    //region Override parent
    @Override
    public String getUserName() {
        return userName;
    }

    @Override
    public void setUserName(String userName) {
        this.userName = userName;

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(UserKey, userName);

        editor.commit();
    }

    @Override
    public String getToken() {
        return token;
    }

    @Override
    public void setToken(String token) {
        this.token = token;

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(TokenKey, token);

        editor.commit();
    }

    @Override
    public SmthConnection getSmthConnection() {
        return SmthConnection.getCurrent();
    }

    @Override
    public Context getAppContext() {
        return this.appContext;
    }
    //endregion

    public void init(AppApplication appContext) {
        setAppContext(appContext);
    }

    protected void load() {
        this.userName = preferences.getString(UserKey, "");
        this.token = preferences.getString(TokenKey, "");
    }

    private void setAppContext(AppApplication appContext) {
        this.appContext = appContext;
        preferences = appContext.getSharedPreferences(AppSettingsPreferenceKey, Context.MODE_PRIVATE);

        this.load();
    }
}
